<template>
  <view class="choose-store-container">
    <uni-nav-bar title="禧易宝商家端">
      <template #right>
        <view
          @click="goToAddStore"
          class="h-88rpx line-height-88rpx text-center color-#000"
        >
          新增店铺
        </view>
      </template>
    </uni-nav-bar>
    <!-- 内容区域 -->
    <view class="content">
      <!-- 标题 -->
      <view class="title">选择店铺：</view>

      <!-- 店铺列表 -->
      <scroll-view
        class="store-list"
        scroll-y
        :scroll-top="scrollTop"
        @scrolltolower="handleScrollToLower"
      >
        <view v-for="store in storeList" :key="store.id" class="store-card">
          <!-- 店铺名称 -->
          <view class="store-name">{{ store.merchantName }}</view>
          <!-- 店铺地址 -->
          <view v-if="store.storeAddress" class="store-address">
            {{ store.storeAddress }}
          </view>

          <!-- 进入店铺按钮 -->
          <view class="enter-btn" @click="handleEnterStore(store)">
            进入店铺
          </view>
        </view>

        <!-- 空状态 -->
        <view v-if="!loading && storeList.length === 0" class="empty-state">
          <text class="empty-title">您还没有店铺</text>
          <text class="empty-text">快来申请成为禧易宝商家吧</text>
          <view class="apply-btn" @click="goToApplyMerchant">
            申请成为商家
          </view>
        </view>

        <!-- 加载中状态（首次加载） -->
        <view v-if="loading && storeList.length === 0" class="loading-state">
          <uni-load-more status="loading" />
        </view>

        <!-- 触底加载组件 -->
        <LoadMore
          v-if="storeList.length > 0"
          :status="loadMoreStatus"
          @retry="handleLoadMore"
        />
      </scroll-view>
    </view>

    <!-- 底部退出按钮 -->
    <view class="footer">
      <view class="logout-btn" @click="handleLogout">退出</view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRequest } from "ahooks-vue";
import { getStoreList, switchStore } from "@/api/user";
import { removeToken } from "@/utils/request";
import { useStoreStore } from "@/store/modules/store";
import { useUserStore } from "@/store/modules/user";
import LoadMore from "@/components/common/LoadMore/LoadMore.vue";
import { hardReloadToHome } from "@/utils/hardReload";

// 使用 Pinia store
const storeStore = useStoreStore();
const userStore = useUserStore();

// 响应式数据
const statusBarHeight = ref(44); // 状态栏高度
const storeList = ref([]);
const scrollTop = ref(0); // 滚动位置

// 分页参数
const pageParams = ref({
  offset: 1,
  limit: 10,
});

// 是否有更多数据
const hasMore = ref(true);

// 加载更多状态：loading-加载中, nomore-没有更多, error-加载失败, more-可以加载更多
const loadMoreStatus = ref("more");
const goToAddStore = () => {
  uni.navigateTo({
    url: "/pages/login/partner/partner",
  });
};

// 获取店铺列表
const { loading, run: getStoreListRun } = useRequest(
  (params) =>
    getStoreList({
      userId: userStore.userId,
      ...params,
    }),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("店铺列表获取成功：", response);

      // 接口返回格式：{ code: 2000, message: '操作成功', data: [...] }
      const data = response?.data || [];

      if (data && data.length > 0) {
        // 如果是第一页，直接赋值；否则追加
        if (pageParams.value.offset === 1) {
          storeList.value = data;
        } else {
          storeList.value = [...storeList.value, ...data];
        }

        // 判断是否还有更多数据
        if (data.length < pageParams.value.limit) {
          hasMore.value = false;
          loadMoreStatus.value = "nomore";
        } else {
          hasMore.value = true;
          loadMoreStatus.value = "more";
        }
      } else {
        // 没有数据
        if (pageParams.value.offset === 1) {
          storeList.value = [];
        }
        hasMore.value = false;
        loadMoreStatus.value = "nomore";
      }
    },
    onError: (error) => {
      console.error("获取店铺列表失败：", error);
      loadMoreStatus.value = "error";
      uni.showToast({
        title: "获取店铺列表失败",
        icon: "none",
      });
    },
  },
);

// 初始化加载
const initLoad = () => {
  pageParams.value.offset = 1;
  hasMore.value = true;
  loadMoreStatus.value = "more";
  getStoreListRun(pageParams.value);
};

// 加载更多
const handleLoadMore = () => {
  if (loading.value || !hasMore.value) return;

  loadMoreStatus.value = "loading";
  pageParams.value.offset += 1;
  getStoreListRun(pageParams.value);
};

// 触底加载
const handleScrollToLower = () => {
  handleLoadMore();
};

// 进入店铺加载状态
const enterLoading = ref(false);

// 调用切换店铺接口
const { run: switchStoreRun } = useRequest(
  (data) => switchStore(data),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("切换店铺接口调用成功：", response);

      uni.showToast({
        title: "进入成功",
        icon: "none",
        duration: 1500,
      });

      setTimeout(() => {
        enterLoading.value = false;
        console.log("🔄 准备强制刷新到首页...");
        // 强制刷新到首页，确保使用最新的店铺ID
        hardReloadToHome();
      }, 800);
    },
    onError: (error) => {
      console.error("切换店铺接口调用失败：", error);
      enterLoading.value = false;
      uni.showToast({
        title: "进入店铺失败",
        icon: "none",
      });
    },
  }
);

// 处理进入店铺
const handleEnterStore = (store) => {
  if (enterLoading.value) return;

  console.log("选择店铺：", store);

  enterLoading.value = true;

  // 使用 Pinia 保存店铺信息
  storeStore.setStoreInfo(store);
  try {
    const storeData = {
      storeId: store.id,
      currentStore: store,
      merchantName: store.merchantName || "",
    };
    uni.setStorageSync("store", storeData);
    console.log("✅ 店铺信息已同步到 localStorage：", storeData);
  } catch (e) {
    console.error("❌ 持久化店铺信息失败：", e);
  }

  // 调用切换店铺接口
  switchStoreRun({
    merchantId: store.id,
    userId: userStore.userId,
  });
};

// 跳转到申请成为商家页面
const goToApplyMerchant = () => {
  uni.navigateTo({
    url: "/pages/login/partner/partner",
  });
};

// 退出登录
const handleLogout = () => {
  uni.showModal({
    title: "提示",
    content: "确定要退出登录吗？",
    confirmColor: "#ffbb00",
    success: (res) => {
      if (res.confirm) {
        // 清除登录状态
        try {
          removeToken();
          storeStore.clearStoreInfo(); // 清除店铺信息
          userStore.clearUserInfo(); // 清除用户信息
          uni.removeStorageSync("storeInfo");
          uni.removeStorageSync("merchantInfo");

          console.log("已清除所有登录信息");

          uni.showToast({
            title: "已退出登录",
            icon: "none",
            duration: 1500,
          });

          setTimeout(() => {
            uni.reLaunch({
              url: "/pages/login/login",
            });
          }, 1500);
        } catch (error) {
          console.error("清除登录信息失败:", error);
          uni.reLaunch({
            url: "/pages/login/login",
          });
        }
      }
    },
  });
};

// 生命周期
onMounted(() => {
  // 获取系统信息
  uni.getSystemInfo({
    success: (res) => {
      statusBarHeight.value = res.statusBarHeight || 44;
    },
  });

  // 初始化加载店铺列表
  initLoad();
});
</script>

<style scoped lang="scss">
.choose-store-container {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
  padding-bottom: env(safe-area-inset-bottom);
}

.status-bar {
  width: 100%;
  background: transparent;
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 40rpx 32rpx;
}

.title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 40rpx;
}

.store-list {
  flex: 1;
  height: 100%;
}

.store-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx 32rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.store-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  text-align: center;
  margin-bottom: 16rpx;
}

.store-address {
  font-size: 26rpx;
  color: #999;
  text-align: center;
  margin-bottom: 32rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.enter-btn {
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  background: #ffbb00;
  color: #333;
  font-size: 32rpx;
  font-weight: 600;
  border-radius: 50rpx;
  transition: all 0.3s ease;

  &:active {
    opacity: 0.8;
    transform: scale(0.98);
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 40rpx;
  background: #fff;
  border-radius: 20rpx;
  margin-top: 40rpx;
}

.empty-logo {
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 40rpx;
  opacity: 0.6;
}

.empty-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 16rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 60rpx;
}

.apply-btn {
  width: 400rpx;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  background: #ffbb00;
  color: #333;
  font-size: 32rpx;
  font-weight: 600;
  border-radius: 50rpx;
  box-shadow: 0 4rpx 20rpx rgba(255, 187, 0, 0.3);
  transition: all 0.3s ease;

  &:active {
    opacity: 0.8;
    transform: scale(0.98);
  }
}

.loading-state {
  display: flex;
  justify-content: center;
  padding: 100rpx 0;
}

.footer {
  padding: 32rpx;
  background: #fff;
  padding-bottom: calc(32rpx + env(safe-area-inset-bottom));
}

.logout-btn {
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  background: #ffbb00;
  color: #333;
  font-size: 32rpx;
  font-weight: 600;
  border-radius: 50rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;

  &:active {
    opacity: 0.8;
    transform: scale(0.98);
  }
}
</style>
